import axios from 'axios'
import router from '../router';
import qs from 'qs';
import {
  Message,
  MessageBox
} from 'element-ui'
import { getToken } from '../util/getToken';

// 请求拦截器
axios.interceptors.request.use((config) => {
  if (getToken('loginCookie')) {
      config.headers['Authorization'] = getToken('loginCookie'); //携带token
  }
  return config;
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use((response) => {
  //能连通接口就会进入这里  这里对接口返回值进行判断
  let {
    code,
    message
  } = response.data
  if (code != 0) {
    Message({
      message: message || 'error',
      type: 'warning'
    })
  }
  return response.data; //此处可以只返回后端传出的数据（第一层data是axios封装的）
}, (error) => {
  if (error.response.status == 401) {//登录过期
      MessageBox.confirm('登录已过期，请重新登录！', '提示', {
        confirmButtonText: '确定',
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        sessionStorage.clear();//清除缓存
        router.push({path: '/login'});//返回登录页
      })
  }
  return Promise.reject(error)
})
class http {
  constructor(baseUrl) {
    this.needLoading = false;
    this.withCredentials = false;
    this.baseUrl = baseUrl
  }

  http(options, config) {
    const {
      method,
      url,
      body = {},
      responseType = ""
    } = options;
    const postHeader = {
      "content-type": "application/x-www-form-urlencoded"
    }
    let params;
    if (method === "get") params = body;
    return axios({
      method,
      baseURL: this.baseUrl,
      url,
      data: body,
      params,
      paramsSerializer: function (params) {
        return qs.stringify(params, {
          arrayFormat: "repeat"
        });
      },
      headers: method === "get" ? {
        "Content-Type": "application/json;charset=UTF-8",
      } : postHeader,
      responseType,
      httpCancel: false,
      ...config,
    });
  }
}

export default http;